ARCH ?= riscv64

ifeq ($(ARCH), riscv64)
    CXX = ${ARCH}-linux-gnu-g++
    TARGET = tinybpt
    OPENSSL_INCLUDE_DIR = /usr/local/openssl/riscv64/include
    OPENSSL_LIBRARIES = /usr/local/openssl/riscv64/lib
    CXXFLAGS = -flto -fno-rtti -Wall -I./include -I$(OPENSSL_INCLUDE_DIR) -Os -O2 -DCPPHTTPLIB_OPENSSL_SUPPORT
    LDFLAGS = -static -flto  -L$(OPENSSL_LIBRARIES) -w -s
    LIBS = -lssl -lcrypto
    STRIP = ${ARCH}-linux-gnu-strip
else ifeq ($(ARCH), x86_64)
    CXX = g++
    TARGET = tinybpt
    OPENSSL_INCLUDE_DIR = /usr/local/openssl/include
    OPENSSL_LIBRARIES = /usr/local/openssl/lib
    CXXFLAGS = -Wall -I./include -I$(OPENSSL_INCLUDE_DIR) -O2 -DCPPHTTPLIB_OPENSSL_SUPPORT
    LDFLAGS = -L$(OPENSSL_LIBRARIES)
    LIBS = -lssl -lcrypto
    STRIP = strip
else
    $(error "Unsupported platform $(ARCH), please use riscv64 or x86_64")
endif

OBJ_DIR = bin
SRC_DIR = src

SRC_FILES = $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES = $(patsubst $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.o, $(SRC_FILES))

all: check $(TARGET)

$(TARGET): $(OBJ_DIR)/main.o $(OBJ_DIR)/tinybpt.o $(OBJ_DIR)/json_utils.o $(OBJ_DIR)/utils.o
	$(CXX) $^ -o $@ $(LDFLAGS) $(LIBS) -O2
	$(STRIP) $@ 

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
	@mkdir -p $(OBJ_DIR)
	$(CXX) $(CXXFLAGS) -c $< -o $@

check:
	@for header in $(wildcard include/*.h); do \
		if [ ! -f $$header ]; then \
			echo "Error: Header file $$header not found!"; \
			exit 1; \
		fi \
	done
	@for lib in libssl libcrypto; do \
		if ! pkg-config --exists $$lib; then \
			echo "Error: Library $$lib not found!"; \
			exit 1; \
		fi \
	done

install: $(TARGET)
	@platform=$$(uname -m); \
	if [ "$$platform" = "$(ARCH)" ]; then \
		mkdir -p ./output/etc/tinybpt && mkdir -p ./output/etc/ssl/certs && mkdir -p ./output/bin; \
		cp $(TARGET) ./output/bin/ && cp tinybpt_db.json ./output/etc/tinybpt/ && cp cacert.pem ./output/etc/ssl/certs/; \
		echo "TinyBPT installed successfully, please check the output directory"; \
	else \
		echo "Error: Unsupported platform $$platform"; \
		exit 1; \
	fi

clean:
	rm -rf $(OBJ_DIR) $(TARGET)

.PHONY: clean check install